<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!--      <crudOperation :permission="permission" />-->
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="文献ID">
            <el-input v-model="form.docId" style="width: 370px;"readonly="true"/>
          </el-form-item>
          <el-form-item label="文件名称">
            <el-input v-model="form.filename" style="width: 370px;" readonly="true"/>
          </el-form-item>
          <el-form-item label="创建者">
            <el-input v-model="form.createBy" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-input v-model="form.createTime" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="修改者">
            <el-input v-model="form.updateBy" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="修改时间">
            <el-input v-model="form.updateTime" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <div>
        <el-col :span="6">
          <el-input v-model="this.$props.selection.mnName" readonly>
            <template slot="prepend">题名</template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-input v-model="this.$props.selection.id" readonly>
            <template slot="prepend">古籍文献编号</template>
          </el-input>
        </el-col>
      </div>
      <div>
        <el-button type="primary" @click="upload">上传图片</el-button>
        <el-button type="primary" @click="updateValue">返回</el-button>
      </div>

    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-upload
        multiple
        :limit="10"
        class="file-box"
        ref="upload"
        action="/upload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :file-list="images"
        list-type="picture"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>

        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitFile()">上传到服务器
        </el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <el-row :gutter="20">
        <el-col v-for="url in imageurls" :span="6">
          <el-image
            style="width: 100px; height: 100px"
            :src="url"
            fit="fill"></el-image>
        </el-col>
      </el-row>
    </el-dialog>
    <!--表格渲染-->
    <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
              @selection-change="crud.selectionChangeHandler">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="id" label="id"/>
      <el-table-column prop="docId" label="文献ID "/>
      <el-table-column prop="filename" label="文件名称"/>
      <el-table-column prop="path" label="照片" align="center">
        <template slot-scope="scope">
          <el-image
            :src="baseApi + '/file' +scope.row.path"
            :preview-src-list="[baseApi + '/file' + scope.row.path]"
            fit="contain"
            lazy
            class="el-avatar"
          >
            <div slot="error">
              <i class="el-icon-document"/>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建者"/>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column prop="updateBy" label="修改者"/>
      <el-table-column prop="updateTime" label="修改时间"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            changeEnabled
            @change="changeState(scope.row,scope.row.status)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination/>
  </div>
</template>

<script>
import crudDocPicture, {uploadImages} from '@/api/literatureManagement/docPicture'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import {mapGetters} from 'vuex'
import {getToken} from "@/utils/auth";


const defaultForm = {
  id: null,
  docId: null,
  filename: null,
  path: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null,
  status: null
}
export default {
  props: {
    selection: Object
  },
  name: 'DocPicture',
  components: {pagination, crudOperation, rrOperation, udOperation},
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '文献图片管理',
      url: 'api/docPicture',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: {...crudDocPicture}
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'docPicture:add'],
        edit: ['admin', 'docPicture:edit'],
        del: ['admin', 'docPicture:del']
      },
      images: [],
      imageurls: [],
      rules: {},
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      dialogVisible: false,
      isShow: true
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.params.docId= this.$props.selection.id
      return true
    },
    changeState(data, val) {
      this.$confirm('此操作将修改状态值为 ' + val + ' 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudDocPicture.edit(data).then(res => {
          this.$message({
            type: 'waring',
            message: '修改成功'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    upload() {
        this.dialogVisible = true
    },
    updateValue() {
      this.$emit('update-value', 1);
    },
    handleRemove(file, fileList) {
      this.images = fileList
      console.log("移除文件列表时的钩子", file);
    },
    //点击某个文件时的钩子
    handlePreview(file) {
      console.log("点击某个文件时的钩子", file);
    },
    //添加到上传列表时的钩子
    handleChange(file, fileList) {
      this.images = fileList
      console.log("添加到上传列表时的钩子", file)
    },
    //文件超出个数限制时的钩子
    handleExceed() {
      this.$message.warning("文件超出10个")
      console.log("文件超出个数限制时的钩子")
    },
    getImages() {
      this.$axios.get("/filelist")
        .then(response => {
          this.imageurls = response.data
          console.log("获取图片列表成功")
        })
        .catch(error => {
          this.$message.error("获取图片列表失败")
        })
    },
    submitFile() {
      if (this.images.length === 0) {
        this.$message.warning("请选择文件")
        return
      }
      const formData = new FormData();
      this.images.forEach(file => {
        formData.append("images", file.raw) //将文件传到表单中，files属性是后端接受的参数名
      })
      formData.append("docId", this.$props.selection.id)
      uploadImages(formData).then(res => {
        this.$message({
          type: 'success',
          message: '图片上传成功!'
        })
        this.images = []
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '图片上传失败!'
        })
      })
    },
  },
  computed: {
    ...
      mapGetters([
        'baseApi',
        'fileUploadApi',
        'imagesUploadApi'
      ]),

  },
  mounted() {
    // getPictureList(this.$props.selection.id).then(res => {
    //   console.log(this.$props.selection)
    //   this.tableDate = res;
    // })
  }
}
</script>

<style scoped>

</style>
